const dayjs = require('../../config/libs_config').dayjs;
const BaseModel = require('./base_model');

/**
 * 项目领域模型
 * 封装项目业务逻辑与规则
 */
class ProjectModel extends BaseModel {
    constructor(data = {}) {
        super(data);
        // 基本属性
        this._id = data._id || '';
        this.projectType = data.projectType || '';
        this.model = data.model || '';
        this.projectTypeName = data.projectTypeName || '';
        this.customerName = data.customerName || '';
        this.startDate = data.startDate || '';
        this.deadline = data.deadline || '';
        this.description = data.description || '';
        this.status = data.level1 || 0;
        this.statusText = data.statusDesc || '草稿';
        this.priority = data.priority || 'normal';
        this.department = data.department || '待定';
        this.leader = data.leader || '待定';
        this.leaderId = data.leaderId || -1;
    
        // 类型特定字段
        this.workTemp = data.workTemp || '';
        this.certification = data.certification || '';
        this.conformalCoating = data.conformalCoating || '';
        // ... 其他字段
    
        // 计算属性
        this.isActive = this.status < 99;
        
        // dayjs 日期处理
        this.isOverdue = this.deadline ? 
            dayjs().isAfter(dayjs(this.deadline)) : false;
        
        this.daysTillDeadline = this.deadline ? 
            dayjs(this.deadline).diff(dayjs(), 'day') : 0;
    }
    
    /**
     * 检查项目是否可编辑
     */
    canEdit() {
        return this.status < 10; // 假设状态大于10的项目不可编辑
    }
    
    /**
     * 获取项目优先级标识
     */
    getPriorityFlag() {
        const map = {
            'low': '低',
            'normal': '中',
            'high': '高',
            'urgent': '紧急'
        };
        return map[this.priority] || '中';
    }
    
    /**
     * 格式化展示日期
     */
    getFormattedDate(dateField) {
        if (!this[dateField]) return '';
        return dayjs(this[dateField]).format('YYYY-MM-DD');
    }
    
    /**
     * 转换为存储格式
     */
    toStorage() {
        // 转换日期格式
        const data = {...this};
    
        if (data.startDate && typeof data.startDate === 'string') {
            data.startDate = dayjs(data.startDate).valueOf();
        }
    
        if (data.deadline && typeof data.deadline === 'string') {
            data.deadline = dayjs(data.deadline).valueOf();
        }
    
        // 设置级别
        data.level1 = this.status;
    
        return data;
    }
    
    /**
     * 验证项目数据是否有效
     */
    validate() {
        const errors = {};
    
        if (!this.projectType) errors.projectType = '项目类型不能为空';
        if (!this.customerName) errors.customerName = '客户名称不能为空';
        if (!this.deadline) errors.deadline = '截止日期不能为空';
    
        return {
            valid: Object.keys(errors).length === 0,
            errors
        };
    }
}

module.exports = ProjectModel; 